<template>
  <div class="user-management">
    <el-card>
      <!-- 用户列表 -->
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="180" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="role" label="角色" width="180">
          <template slot-scope="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'success' : 'info'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="button-group">
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteUser(scope.row)"
                :disabled="scope.row.role === 'admin' || (user && user.id === scope.row.id)"
              >
                删除
              </el-button>
              <el-button
                size="mini"
                :type="scope.row.role === 'admin' ? 'info' : 'primary'"
                @click="handleChangeRole(scope.row)"
                :disabled="scope.row.role === 'admin' || (user && user.id === scope.row.id)"
              >
                {{ scope.row.role === 'admin' ? '已是管理员' : '设为管理员' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="mt-20">
      <!-- 柜子使用记录 -->
      <div slot="header" class="clearfix">
        <span>所有用户柜子使用记录</span>
      </div>
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="输入柜子编号、使用者或状态进行检索"
          prefix-icon="el-icon-search"
          clearable
        ></el-input>
      </div>
      <el-table :data="filteredRecords" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="cabinetId" label="柜子编号" width="120" />
        <el-table-column prop="username" label="使用者" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'in_use' ? 'success' : 'info'">
              {{ scope.row.status === 'completed' ? '已完成' : '使用中' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';

export default {
  name: 'UserManagement',
  data() {
    return {
      searchQuery: ''
    };
  },
  computed: {
    ...mapState(['users', 'user']),
    ...mapGetters(['getCabinetRecords']),
    filteredRecords() {
      const query = this.searchQuery.toLowerCase();
      return this.getCabinetRecords.filter(record => {
        return (
          record.cabinetId.toLowerCase().includes(query) ||
          record.username.toLowerCase().includes(query) ||
          (record.status === 'completed' ? '已完成' : '使用中').includes(query)
        );
      });
    }
  },
  methods: {
    ...mapActions(['deleteUser', 'updateUserRole']),
    async handleDeleteUser(user) {
      try {
        await this.$confirm(`确定要删除用户 "${user.username}" 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await this.deleteUser(user.id);
        this.$message.success('删除用户成功');
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '删除用户失败');
        }
      }
    },
    async handleChangeRole(user) {
      try {
         await this.$confirm(`确定要将用户 "${user.username}" 设为管理员吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await this.updateUserRole({ userId: user.id, role: 'admin' });
        this.$message.success(`用户 "${user.username}" 已设为管理员`);
      } catch (error) {
        if (error !== 'cancel') {
           this.$message.error(error.message || '设置管理员失败');
        }
      }
    },
  },
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  flex-wrap: wrap; /* Allow buttons to wrap to the next line */
  gap: 5px; /* Add some space between buttons */
}

/* Optional: Make buttons stack vertically on very small screens if needed */
/*
@media (max-width: 768px) { // Adjust breakpoint as needed
  .button-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
*/
</style>
